/**
 *  学习目标：Todos 案例
 */
import React, { useEffect, useState } from 'react'
import './styles/base.css'
import './styles/index.css'
import Header from './components/Header/index.js'
import Main from './components/Main/index.js'
import Footer from './components/Footer/index.js'
export default function App() {
  const [list, setList] = useState([
    { id: 1, content: '游戏', flag: true },
    { id: 2, content: '旅游', flag: false },
    { id: 3, content: '音乐', flag: true },
  ])
  const [type, setType] = useState('all')
  useEffect(() => {
    setList(JSON.parse(localStorage.getItem('todos')) || [])
    setType(localStorage.getItem('todos-type') || 'all')
  }, [])
  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(list))
    localStorage.setItem('todos-type', type)
  }, [list, type])
  const radioCheck = (id) => {
    const newList = list.map(item => {
      if (item.id === id) {
        return { ...item, flag: !item.flag }
      } else {
        return item
      }

    })
    setList(newList)
  }
  const radioRemove = (id) => {
    const newList = list.filter(item => item.id !== id)
    setList(newList)
  }
  const allCheck = (flag) => {
    const newList = list.map(item => ({ ...item, flag: flag }))
    setList(newList)
  }
  const clearCompleted = () => {
    const newList = list.filter(item => !item.flag)
    setList(newList)
  }
  const typeChange = (type) => {
    setType(type)
  }
  const publish = (content) => {
    setList([{ id: Date.now(), content, flag: false }, ...list])
  }
  return (
    <section className='todoapp'>
      {/* 头部 */}
      <Header publish={publish}></Header>
      {/* 主体 */}
      <Main list={list} radioCheck={radioCheck} radioRemove={radioRemove} allCheck={allCheck} type={type}></Main>
      {/* 底部 */}
      <Footer list={list} clearCompleted={clearCompleted} type={type} typeChange={typeChange}></Footer>
    </section>
  )
}

